Binary tree longest consecutive sequence II¶
Time: O(N); Space: O(H); medium
Given a binary tree, find the length(number of nodes) of the longest consecutive sequence(Monotonic and adjacent node values differ by 1) path. The path could be start and end at any node in the tree
Example 1:
Input: root = {TreeNode} [1,2,0,3]
Output: 4
Explanation:
1
/ \
2 0
/
3
0-1-2-3
Example 2:
Input: root = {TreeNode} [3,2,2]
Output: 2
Explanation:
3
/ \
2 2
2-3
[1]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
[2]:
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def longestConsecutiveHelper(root):
if not root:
return 0, 0
left_len = longestConsecutiveHelper(root.left)
right_len = longestConsecutiveHelper(root.right)
cur_inc_len, cur_dec_len = 1, 1
if root.left:
if root.left.val == root.val + 1:
cur_inc_len = max(cur_inc_len, left_len[0] + 1)
elif root.left.val == root.val - 1:
cur_dec_len = max(cur_dec_len, left_len[1] + 1)
if root.right:
if root.right.val == root.val + 1:
cur_inc_len = max(cur_inc_len, right_len[0] + 1)
elif root.right.val == root.val - 1:
cur_dec_len = max(cur_dec_len, right_len[1] + 1)
self.max_len = max(self.max_len, cur_dec_len + cur_inc_len - 1)
return cur_inc_len, cur_dec_len
self.max_len = 0
longestConsecutiveHelper(root)
return self.max_len
[3]:
s = Solution1()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(0)
root.left.left = TreeNode(3)
assert s.longestConsecutive(root) == 4
root = TreeNode(3)
root.left = TreeNode(2)
root.right = TreeNode(2)
assert s.longestConsecutive(root) == 2